<?php

namespace Biz\service\wiki;

use Biz\cache\wiki\GoodsHot;
use Biz\model\wiki\Wiki as mWiki;
use Biz\model\wiki\WikiBasic;
use Biz\module\Classes\wiki\Infos as clsInfos;
use Biz\module\Classes\wiki\WikiMiddle as cWikiMiddle;
use Biz\service\brand\Brand as sBrand;
use Biz\tools\helper\Common;
use Doraemon\tools\ExposeLog;
use Doraemon\tools\HhzClient;
use Doraemon\tools\Hhzurl;
use Doraemon\tools\Log;


class WikiMiddle
{
    const TAB_TYPE = 'simi_wiki';
    const MIDDLEWARE_H5_URL = "/shop/wiki-middle-page";

    /**
     * wiki中间页列表
     * @param array $params
     * @return array
     * @throws \Exception
     */
    public static function getMiddleWikiList(array $params): array
    {
        $wiki_ids = $params['wiki_ids'] ?? [];
        $uid = $params['uid'] ?? 0;
        $list = clsInfos::infos($wiki_ids, clsInfos::FIELDS_GROUP_MIDDLE_LIST, $uid);
        if (HhzClient::isLogExpose()) {
            ExposeLog::recordWikiLog(array_values($list));
        }
        return $list;
    }

    /**
     * 根据品牌id获取品牌信息
     * @param $brand_id
     * @return array|mixed
     */
    public static function getBrandInfo($brand_id): array
    {
        $brandInfo = sBrand::getBrandListByIds4App([$brand_id]);
        $brand_info = $brandInfo[$brand_id];
        return $brand_info ?? [];
    }


    /**
     * 获取品牌中间页wiki_id集合-通过wiki_basic -id 查询
     * @param $wiki_id
     * @param $brand_id
     * @return array|bool
     */
    public static function getBrandWikiBasicIds($wiki_id, $brand_id)
    {
        $info = mWiki::get(['id', 'brand_id', 'last_category_id'], ['id' => $wiki_id]);

        //当前分类
        $category = $info['last_category_id'] ?? '';

        //wiki_basic 查询条件
        $where['brand_id'] = $brand_id;
        $where['basic_state'] = WikiBasic::STATE_ONLINE;
        $basic_info = WikiBasic::select(['id'], $where);
        $basic_ids = array_column($basic_info, 'id');

        $wiki_info = [];
        //wiki查询条件
        if ($basic_ids) {
            $where_wiki['id[!]'] = $wiki_id;
            $where_wiki['basic_id'] = $basic_ids;
            $where_wiki['status[!]'] = mWiki::STATUS_DEL;
            $where_wiki['is_official'] = mwiki::IS_OFFICIAL_Y;
            $where_wiki['is_default'] = mWiki::IS_DEFAULT;
            $where_wiki['brand_id'] = $brand_id;

            $wiki_info = mWiki::select(['id', 'basic_id', 'last_category_id'], $where_wiki);
        }

        $arr = [];
        $hot_arr = [];
        if ($wiki_info) {
            foreach ($wiki_info as $key => $v) {
                if ($category === $v['last_category_id']) {
                    //商品分类数组
                    $arr[] = $v['id'];
                } else {
                    //获取商品品类热度数组
                    $hot_arr[$key]['basic_id'] = $v['basic_id'];
                    $hot_arr[$key]['id'] = $v['id'];
                }
            }
        }

        $basic_ids = $hot_arr ? array_column($hot_arr, 'basic_id') : [];
        $cache_hots = $basic_ids ? GoodsHot::getMulti($basic_ids) : [];
        $cache_ids = array_keys($cache_hots);
        foreach ($hot_arr as $k => $item) {
            if (in_array($item['basic_id'], $cache_ids)) {
                $hot_arr[$k]['hot'] = $cache_hots[$item['basic_id']] ?? 0;
            }
        }
        //取热度
        $hots = array_column($hot_arr, 'hot');
        //按照热度排序hots
        array_multisort($hots, SORT_DESC, $hot_arr);
        //获取热度id集合
        $ids = array_column($hot_arr, 'id');

        $wiki_ids = array_merge([$wiki_id], $arr, $ids);

        return $wiki_ids ?? [];
    }


    /**
     * 获取wiki中间页wiki_id集合
     * @param $wiki_id
     * @param int $uid
     * @param int $type 1:保留当前wiki_id
     * @return array
     */
    public static function getWikiIds($wiki_id, $uid = 0, $type = 1): array
    {
        $params['wiki_id'] = $wiki_id;
        $params['uid'] = $uid;
        //小鹅拼拼直接走兜底方案
        $channel = mWiki::get('channel', ['id' => $wiki_id]);
        if (in_array($channel, [mWiki::CHANNEL_XIAOEPINPIN, mWiki::CHANNEL_AMAZON, mWiki::CHANNEL_XIAOMIYOUPIN])) {
            $wiki_ids = mWiki::selectByWhere([
                'channel' => $channel,
                'id[!]' => $wiki_id,
                'LIMIT' => 20,
                'ORDER' => ['id' => 'DESC']
            ], 'id');
        } else {
            $wiki_ids = cWikiMiddle::getWikiIds($params, self::TAB_TYPE);
        }

        if (!$wiki_ids) {
            //兜底方案
            $wiki_ids = Wiki::getRecommendWikiIds($wiki_id);
        }
        $log = mWiki::log();
        Log::position_info('wiki_list', compact('channel', 'wiki_id', 'wiki_ids', 'log'));
        if ($type == 1) {
            $new_ids = array_merge([$wiki_id], $wiki_ids);
            $new_ids = array_unique($new_ids);
        } else {
            $new_ids = $wiki_ids;
        }
        $ids = [];
        $wikiInfos = Wiki::getWikiBaseInfos($new_ids);
        if ($wikiInfos) {
            //过滤相同basic_id
            $basicArr = [];
            foreach ($new_ids as $wikiId) {
                $info = $wikiInfos[$wikiId] ?? [];
                if ($info && !isset($basicArr[$info['basic_id']])) {
                    $basicArr[$info['basic_id']] = $info['id'];
                    $ids[] = $info['id'];
                }
            }
        } else {
            $ids[] = $wiki_id;
        }
        return $ids;
    }


    /**
     * 详情页推荐
     * @param $wiki_id
     * @param $uid
     * @return array|array[]
     * @throws \Exception
     */
    public static function getAiWikiList($wiki_id, $uid): array
    {
        $wiki_ids = self::getWikiIds($wiki_id, $uid);
        if ($wiki_ids) {
            $list = Wiki::getWikiList($wiki_ids, $uid, Wiki::FIELDS_GROUP_MASONRY_LIST);
        } else {
            $list = Wiki::getRecommendByWikiId($wiki_id, $uid);
        }
        return $list;
    }

    /**
     * 获取中间页连接
     * @param $row
     * @return string
     */
    public static function getMiddleLink($row): string
    {
        $link = Hhzurl::getDomain() . self::MIDDLEWARE_H5_URL . "?wiki_id=" . $row['id'] . "&hhzjump=1";
//        $link = 'hhz://urlb:' . base64_encode($link);
//        $link = 'niceliving://webview/onboarding?protego=' . urlencode(base64_encode(json_encode(['url' => $link])));
        $link = Common::formatFullScreenLink($link);
        return $link;
    }

}
